package com.xinggq.auth.service.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.stereotype.Component;

/**
 * Redis连接池监控配置
 * 提供连接池状态监控
 * 
 * @author xinggq
 * @since 2025-01-26
 */
@Slf4j
@Component
public class RedisPoolMonitorConfig {

    private final RedisConnectionFactory redisConnectionFactory;

    public RedisPoolMonitorConfig(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    /**
     * 检查Redis连接状态
     */
    public boolean checkRedisConnection() {
        try {
            // 测试Redis连接
            redisConnectionFactory.getConnection().ping();
            log.info("Redis连接检查成功");
            return true;
        } catch (Exception e) {
            log.error("Redis连接检查失败", e);
            return false;
        }
    }

    /**
     * 记录连接池状态信息
     * 可以通过定时任务调用此方法来监控连接池状态
     */
    public void logPoolStatus() {
        try {
            if (redisConnectionFactory instanceof LettuceConnectionFactory lettuceFactory) {
              log.info("Redis连接池状态 - 主机: {}:{}, 数据库: {}",
                        lettuceFactory.getHostName(), 
                        lettuceFactory.getPort(), 
                        lettuceFactory.getDatabase());
            }
        } catch (Exception e) {
            log.warn("获取Redis连接池状态失败", e);
        }
    }

    /**
     * 获取连接池配置信息
     */
    public String getPoolInfo() {
        if (redisConnectionFactory instanceof LettuceConnectionFactory lettuceFactory) {
          return String.format("Redis连接池 - %s:%d DB:%d",
                    lettuceFactory.getHostName(), 
                    lettuceFactory.getPort(), 
                    lettuceFactory.getDatabase());
        }
        return "Redis连接池信息不可用";
    }
}